package org.budo.zookeeper.curator.factory;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.springframework.beans.factory.FactoryBean;

import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

/**
 * @author limingwei
 */
@Getter
@Setter
@Slf4j
public class CuratorFrameworkFactoryBean implements FactoryBean<CuratorFramework> {
    private String address;

    private RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, 3);

    @Override
    public CuratorFramework getObject() throws Exception {
        synchronized (CuratorFrameworkFactoryBean.class) {
            log.info("#27 before init curatorFramework, this = " + this);

            CuratorFramework curatorFramework = CuratorFrameworkFactory.newClient(this.getAddress(), this.getRetryPolicy());
            curatorFramework.start();

            log.info("#32 after init&start curatorFramework, curatorFramework=" + curatorFramework + ", this = " + this);
            return curatorFramework;
        }
    }

    @Override
    public Class<?> getObjectType() {
        return CuratorFramework.class;
    }

    @Override
    public boolean isSingleton() {
        return true;
    }
}